<template>
    <div>
        <el-card class="xj-table">
            <div class="xj-table-tree">
                <el-card>
                    <avue-tree ref="treeSysConfig" :option="treeOption" :data="treeData" @node-click="nodeClick">
                        <!-- 图标/文字- 根据根据不同内容展示不同图标,或者不要  -->
                        <!--    <span class="el-tree-node__label" slot-scope="{ node, data }">-->
                        <!--       <i class="el-icon-document-remove"></i>  &nbsp; {{ data.name }}-->
                        <!--   </span>-->
                        <!-- 右键按钮  -->
                        <template #menu="{node}">
                            <div class="avue-tree__item" @click="updRow(node.data,1)"><i class="el-icon-plus"> 顶级</i></div>
                            <div class="avue-tree__item" @click="updRow(node.data,2)"><i class="el-icon-plus"> 子级</i></div>
                            <!--                            <div class="avue-tree__item" @click="updRow(node.data,3)"><i class="el-icon-edit"> 变更父级</i></div>-->
                            <div class="avue-tree__item" @click="updRow(node.data,4)"><i class="el-icon-edit"> 编辑</i></div>
                            <div class="avue-tree__item" @click="updRow(node.data,6)"><i class="el-icon-delete"> 删除</i></div>
                            <div class="avue-tree__item" @click="updRow(node.data,5)"><i class="el-icon-refresh"> 刷新</i></div>
                        </template>
                    </avue-tree>
                </el-card>
            </div>
            <div class="xj-table-list">
                <avue-crud ref="crudSysConfig"
                           :data="data"
                           :option="option"
                           v-model:page="page"
                           v-model:search="search"
                           :table-loading="loading"
                           :cell-style="cellStyle"
                           @on-load="onLoad"
                           @refresh-change="onLoad"
                           @search-change="searchChange"
                           @row-click="handleRowClick">
                    <template #menu-left="{size}">
                        <span><!--  防抖动--> </span>
                    </template>
                    <!-- 列表上进行编辑sort -->
                    <template #sort="{row,index}">
                        <el-input v-model="row.sort" @blur="rowSortBlur(row)" placeholder=""></el-input>
                    </template>

                    <template #menu="{scope,row,size,index}">
                        <el-button type="primary" :size="size" text icon="el-icon-edit" @click="updRow(row,4)">编辑</el-button>
                        <el-button type="primary" :size="size" text icon="el-icon-delete" @click="rowDel(row,index)">删除</el-button>
                    </template>
                </avue-crud>
            </div>
        </el-card>
        <el-dialog draggable :title="rowData.name?'在 - 【'+ rowData.name + '】 - 下新增数据':'添加顶级数据'"
                   v-if="addDialogVisible" v-model="addDialogVisible" :width="dialogWidth" top="6vh" @close="closeDialog">
            <Add @closeDialog="closeDialog" :uri="uri" :rowData="rowData"></Add>
            <span slot="footer" class="dialog-footer"></span>
        </el-dialog>
        <el-dialog draggable :title="'编辑数据 - 【'+rowData.name + '】'" v-if="updDialogVisible" v-model="updDialogVisible" :width="dialogWidth" top="6vh" @close="closeDialog">
            <Upd @closeDialog="closeDialog" :uri="uri" :rowData="rowData"></Upd>
            <span slot="footer" class="dialog-footer"></span>
        </el-dialog>
    </div>
</template>


<script>
import {defineAsyncComponent} from 'vue';

export default {
    components: {
        Add: defineAsyncComponent(() => import('./configAdd.vue')),
        Upd: defineAsyncComponent(() => import('./configUpd.vue')),
        // UpdPid: defineAsyncComponent(() => import('./configPid.vue')),
    },
    data() {
        return {
            treeOption: JSON.parse(JSON.stringify(this.website.treeOption)),
            uri: {
                infoTree: "/api/admin/sys/config/tree",
                infoList: "/api/admin/sys/config/findPage",
                info: "/api/admin/sys/config",
            },
            loading: true,
            dialogWidth: "75%",
            addDialogVisible: false,      // 添加弹层开关状态
            updDialogVisible: false,      // 添加弹层开关状态
            updPidDialogVisible: false,      // 变更父级开关状态
            page: this.website.pageParams,   // 分页参数
            search: {
                pid: "0"
            },                      // 搜索参数
            treeData: [],                 // 左侧树数据
            data: [],                     // 右侧列表数据
            rowData: {},                  // 当前选中行数据(左树列表)
            option: {},                    // 列表配置
            treeRowId: ""                 // 左树当前选中的id
        }
    },
    activated:
        function () {
            this.crud.doLayout(this, this.$refs.crudSysConfig)
        }
    ,
    mounted() {
        // 2、右侧表格配置(树结构)
        this.option = JSON.parse(JSON.stringify(this.website.optionConfig));
        this.option.index = true;
        this.option.cellBtnt = true
        this.option.column = [
            {
                label: '类型',
                prop: 'type',
                type: 'select',
                search: true,
                searchSpan: 5,
                filterable: true,
                overHidden: true,
                dicData: this.dict.get('CONFIG_TYPE'),
            },
            {
                label: '名称',
                prop: 'name',
                search: true,
                searchSpan: 5,
                overHidden: true,
            },
            {
                label: 'code',
                prop: 'code',
                search: true,
                searchSpan: 5,
                overHidden: true,
            },
            {
                label: '值',
                prop: 'content',
                search: false,
                searchSpan: 5,
                overHidden: true,
                html: true,
                formatter: (row) => {
                    // 图片
                    if (row.type === 1) {
                        if (row.content == null || row.content == '') {
                            return "";
                        } else {
                            let imgs = row.content.split(",");
                            let html = "";
                            imgs.forEach(item => html += "<img src='" + item + "'  style='height: 40px;width: 50px;margin-top: 10px'>")
                            return html;
                        }
                    }
                    // 开关
                    if (row.type === 2) {
                        return row.content === 'true' ? "<span style='color: #2dc26b'>" + row.content + " <span>" : "<span style='color: red'>" + row.content + " <span>";
                    }
                    // 其他
                    return row.content;
                }
            },
            {
                label: '排序',
                prop: 'sort',
                search: false,
                searchSpan: 5,
                overHidden: true,
            },
            {
                label: '描述',
                prop: 'desc',
                search: false,
                searchSpan: 5,
                overHidden: true,
            },
            // {
            //     label: '扩展字段1',
            //     prop: 'ext1',
            //     search: false,
            //     searchSpan: 5,
            //     overHidden: true,
            // },
            // {
            //     label: '扩展字段2',
            //     prop: 'ext2',
            //     search: false,
            //     searchSpan: 5,
            //     overHidden: true,
            // },
            // {
            //     label: '扩展字段3',
            //     prop: 'ext3',
            //     search: false,
            //     searchSpan: 5,
            //     overHidden: true,
            // },
        ]
    },
    created() {
        // 1、左侧菜单配置
        this.treeOption.props.label = "name";
        this.treeOption.props.children = "children";
        this.treeOption.menu = true;
        // 查询左侧菜单数据
        this.findLeftTree();
    },

    methods: {
        onLoad() {
            this.crud.list(this, true);
            this.crud.doLayout(this, this.$refs.crudSysConfig);
        },
        searchChange(params, done) {
            this.page.currentPage = 1;
            this.onLoad();
            done();
        },
        async findLeftTree() {
            let res = await this.crud.get(this.uri.infoTree);
            this.pidDic = JSON.parse(JSON.stringify(res.data.data));
            this.pidDic.unshift({id: '0', name: '无'});
            this.treeData = res.data.data;
            this.treeData.unshift({id: '0', name: '顶级数据'});
            this.treeData.unshift({id: '', name: '全部数据'});
            // 设置默认选中和自动展开
            if (this.treeRowId != null && this.treeRowId !== '') {
                this.treeOption.defaultExpandedKeys = [this.treeRowId];
                this.$nextTick(() => {
                    this.$refs.treeSysConfig.setCurrentKey(this.treeRowId);
                })
            }
        },

        // 点击左左侧数据 重置右列表数据
        nodeClick(data) {
            //this.$message.success(JSON.stringify(data))
            this.rowData = data;
            this.search.pid = data.id;
            this.onLoad();
        },

        closeDialog(isRefresh, dataId) {
            this.addDialogVisible = false;
            this.updDialogVisible = false;
            this.updPidDialogVisible = false;
            this.rowData = {};
            if (isRefresh != null && isRefresh) {
                this.onLoad();
            }
            // 左侧树结构数据更新
            if (dataId != null && dataId) {
                this.treeRowId = dataId;
                this.findLeftTree();
            }
        },
        // 行操作
        updRow(row, type) {
            this.rowData = row;
            switch (type) {
                case 1:
                    // +顶级数据
                    this.rowData = {};
                    this.rowData.operationType = 1;
                    this.rowData.pidDic = this.pidDic;
                    this.addDialogVisible = true;
                    break;
                case 2:
                    // +子级数据
                    this.rowData.operationType = 2;
                    this.rowData.pidDic = this.pidDic;
                    this.addDialogVisible = true;
                    break;
                case 3:
                    // 变更父级
                    this.updPidDialogVisible = true;
                    break;
                case 4:
                    // 编辑
                    this.rowData.pidDic = this.pidDic;
                    this.updDialogVisible = true;
                    break;
                case 5:
                    // 刷新
                    this.findLeftTree()
                    break;
                case 6:
                    // 删除(左边树上删除)
                    this.rowDel(row);
                    break;
                default:
                    this.$message.error('操作类型错误');
                    break;
            }
        },
        // 行删除
        rowDel(row) {
            this.$confirm('此操作将永久删除【' + row.name + '】以及子数据,是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.crud.del(this.uri.info + "/" + row.id).then((res) => {
                    if(res.data.code === 200){
                        // 删除后刷新列表数据
                        this.onLoad();
                        // 更新树结构数据
                        this.$refs.treeSysConfig.remove(row.id)
                    }
                })
            })
        },
        // 排序
        rowSortBlur(row) {
            if (this.rowData.sort != row.sort) {
                this.crud.put(this.uri.info + "/" + row.id, {code: row.code, sort: row.sort});
            }
        },
        // 点击保存行数据(供行操作的任意地方获取数据)
        handleRowClick(row) {
            this.rowData = JSON.parse(JSON.stringify(row));
        },
        // 自动配置,单元格样式数字，对指定列设置字体颜色,大小，粗细等
        cellStyle({row, column}) {
            if (column.property == "type") {
                // fontWeight: 'bold',fontSize: '20'
                if (row.type == 0) {
                    return {color: 'green'}
                } else if (row.type == 1) {
                    return {color: '#20B2AA'}
                } else if (row.type == 2) {
                    return {color: '#9932CC'}
                }
            }
        },
    }
}
</script>
